//
//  Tools.m
//  TianXingPlanet
//
//  Created by Zeaple on 15/8/12.
//  Copyright (c) 2015年 Zyii. All rights reserved.
//

#import "Tools.h"
#import "AFNetworking.h"
#import "MBProgressHUD+JDragon.h"
#import "MBProgressHUD+LJ.h"
#import "AppDelegate.h"
#import <CommonCrypto/CommonCrypto.h>
static NSString *const globalCommunicationWithSeverUrl =FKGWAPI;

@implementation Tools

#pragma mark - JsonDataToString
+ (NSString *)stringConvertToJsonString:(id)aString {
    NSData *jsonData = [NSJSONSerialization
                           dataWithJSONObject:aString options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
#pragma mark-ViewController
+(void)popViewControllerAfterDelay:(NSInteger)delay WithController:(UIViewController *)viewController {
    Tools *instanceTool = [[Tools alloc]init];
    [instanceTool performSelector:@selector(popAfterDelay:) withObject:viewController afterDelay:delay];
}

-(void)popAfterDelay:(UIViewController *)vc {
    [vc.navigationController popViewControllerAnimated:YES];
}
//dismissController
+(void)dismissViewControllerAfterDelay:(NSInteger)delay WithController:(UIViewController *)viewController {
    Tools *instanceTool = [[Tools alloc]init];
    [instanceTool performSelector:@selector(dismissAfterDelay:) withObject:viewController afterDelay:delay];
}
-(void)dismissAfterDelay:(UIViewController *)vc {
    [vc dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark-将手机号替换成180****0811形式
+(NSString *)transferPhoneNumToSecretTypeWithNum:(NSString *)phoneNum {
    NSRange secretPhoneRange;
    secretPhoneRange.length = 4;
    secretPhoneRange.location = 3;
    NSString *secretPhoneTypeStr = [phoneNum stringByReplacingCharactersInRange:secretPhoneRange withString:@"****"];
    return secretPhoneTypeStr;
}

+ (void)AFNetworkingRequestTypeGETWithUrl:(NSString *)url  afterResultBlock:(afterResultBlock)resultAct{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [self customSecurityPolicy];
    NSString *networkurl;
    if([url containsString:@"http"]){
        networkurl  = url;
    }else{
        networkurl = [NSString stringWithFormat:globalCommunicationWithSeverUrl,FKGWIP,url];
    }
    DLog(@"%@",networkurl);
    [manager GET:networkurl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (!responseObject) {
//            [MBProgressHUD showErrorWithStatus:@"No Data!"];
            [MBProgressHUD showErrorMessage:@"No Data!"];
        } else {
            resultAct(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (error.localizedDescription) {
            if (error.code == -999) {
//                [SVProgressHUD dismiss];
                [MBProgressHUD dismiss];
            } else {
//                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                [MBProgressHUD showErrorMessage:error.localizedDescription];
            }
        }
    }];
}

+ (void)AFNetworkingRequestTypeGETWithUrl:(NSString *)url paramters:(id)paramters afterResultBlock:(afterResultBlock)resultAct{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [self customSecurityPolicy];
    NSString *networkurl;
    if([url containsString:@"http"]){
        networkurl  = url;
    }else{
        networkurl = [NSString stringWithFormat:globalCommunicationWithSeverUrl,FKGWIP,url];
    }
    DLog(@"%@",networkurl);
    [manager GET:networkurl parameters:paramters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (!responseObject) {
//            [SVProgressHUD showErrorWithStatus:@"No Data!"];
             [MBProgressHUD showErrorMessage:@"No Data!"];
        } else {
            resultAct(responseObject);
        }

    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (error.localizedDescription) {
            if (error.code == -999) {
//                [SVProgressHUD dismiss];
                [MBProgressHUD dismiss];
            } else {
//                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                 [MBProgressHUD showErrorMessage:error.localizedDescription];
            }
        }

    }];
}

//Wish To Handle Error Action
+ (void)AFNetworkingRequestTypeGETWithUrl:(NSString *)url paramters:(id)paramters afterResultBlock:(afterResultBlock)resultAct handleErrorBlock:(errorActionBlock)errorAct{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [self customSecurityPolicy];
    NSString *networkurl;
    if([url containsString:@"http"]){
        networkurl  = url;
    }else{
        networkurl = [NSString stringWithFormat:globalCommunicationWithSeverUrl,FKGWIP,url];
    }
    DLog(@"%@",networkurl);
    [manager GET:networkurl parameters:paramters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (!responseObject) {
//            [SVProgressHUD showErrorWithStatus:@"No Data!"];
            [MBProgressHUD showErrorMessage:@"No Data!"];

            
        } else {
            resultAct(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (error.localizedDescription) {
            if (error.code == -999) {
//                [SVProgressHUD dismiss];
                [MBProgressHUD dismiss];
            } else {
//                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            }
            errorAct(error);
        }
    }];
}

+ (void)AFNetworkingRequestTypeGetWithUrl:(NSString *)url MultiParamters:(id)paramters afterResultBlock:(afterResultBlock)resultAct{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.securityPolicy = [self customSecurityPolicy];
    NSString *networkurl;
    if([url containsString:@"http"]){
        networkurl  = url;
    }else{
        networkurl = [NSString stringWithFormat:globalCommunicationWithSeverUrl,FKGWIP,url];
    }
    DLog(@"%@",networkurl);
    [manager GET:networkurl parameters:paramters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        if (!responseObject) {
//            [SVProgressHUD showErrorWithStatus:@"No Data!"];
               [MBProgressHUD showErrorMessage:@"No Data!"];
        } else {
            resultAct(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (error.localizedDescription) {
            if (error.code == -999) {
//                [SVProgressHUD dismiss];
                [MBProgressHUD dismiss];
            } else {
//                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                   [MBProgressHUD showErrorMessage:error.localizedDescription];
            }
        }
    }];
}

//Post 请求
+ (void)AFNetworkingRequestTypePostWithUrl:(NSString *)url paramters:(id)paramters afterResultBlock:(afterResultBlock)resultAct{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [self customSecurityPolicy];
    NSString *networkurl;
    if([url containsString:@"http"]){
        networkurl  = url;
    }else{
        networkurl = [NSString stringWithFormat:globalCommunicationWithSeverUrl,FKGWIP,url];
    }
    DLog(@"%@",networkurl);
    [manager POST:networkurl parameters:paramters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!responseObject) {
            [MBProgressHUD showErrorMessage:@"No Data!"];
        } else {
            resultAct(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD dismiss];
        [MBProgressHUD dismissHUD];
        if (error.localizedDescription) {
            if (error.code == -999) {
                [MBProgressHUD dismiss];
            } else {
                DLog(@"--%ld--%@", error.code,error.localizedDescription);
                if([error.localizedDescription containsString:@"Could not connect to the server"]){
//                    [MBProgressHUD showTipMessageInWindow:@"服务器繁忙，请稍后再试"];
                }
            }
        }
    }];
}

+ (void)AFNetworkingRequestTypePostWithUrl:(NSString *)url paramters:(id)paramters afterResultBlock:(afterResultBlock)resultAct handleErrorBlock:(errorActionBlock)errorAct{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [self customSecurityPolicy];
    NSString *networkurl;
    if([url containsString:@"http"]){
        networkurl  = url;
    }else{
        networkurl = [NSString stringWithFormat:globalCommunicationWithSeverUrl,FKGWIP,url];
    }
    DLog(@"%@",networkurl);

    [manager POST:networkurl parameters:paramters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!responseObject) {
//            [SVProgressHUD showErrorWithStatus:@"No Data!"];
            [MBProgressHUD showErrorMessage:@"No Data!"];

        } else {
            resultAct(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.localizedDescription) {
            if (error.code == -999) {
//                [SVProgressHUD dismiss];
                [MBProgressHUD dismiss];
            } else {
//                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                [MBProgressHUD showErrorMessage:error.localizedDescription];

            }
        }
        errorAct(error);
    }];
}

//上传头像
+ (void)AFNetworkingUploadImage:(NSData *)imageData withUrl:(NSString*)url paramters:(id)paramters afterResultBlock:(afterResultBlock)resultAct{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [self customSecurityPolicy];
    NSString *networkurl;
    if([url containsString:@"http"]){
        networkurl  = url;
    }else{
        networkurl = [NSString stringWithFormat:globalCommunicationWithSeverUrl,FKGWIP,url];
    }
    DLog(@"%@",networkurl);
    [manager POST:networkurl parameters:paramters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpeg" mimeType:@"image/JPEG"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        resultAct(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.localizedDescription) {
            if (error.code == -999) {
//                [SVProgressHUD dismiss];
                [MBProgressHUD dismiss];
            } else {
//                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                      [MBProgressHUD showErrorMessage:error.localizedDescription];
                DLog(@"%@", error.localizedDescription);
            }
        }
    }];
}

+ (void)cancelAllNetworkRequests {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.operationQueue cancelAllOperations];
}

+ (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"cfkj_https" ofType:@"cer"];
    //证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    //AFSSLPinningModeNone         不做任何验证，只要服务器返回了证书就通过
    //AFSSLPinningModePublicKey    只验证公钥部分，只要公钥部分一致就验证通过
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    securityPolicy.pinnedCertificates = [NSSet setWithObjects:certData, nil];
    return securityPolicy;
}


+ (NSString *)MD5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr,strlen(cStr),result);
    NSString *d5Str = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                       result[0],result[1],result[2],result[3],result[4],result[5],result[6],result[7],
                       result[8],result[9],result[10],result[11],result[12],result[13],result[14],result[15]];
    DLog(@"MD5--%@",d5Str);
    NSString *str1 = [d5Str substringFromIndex:8];
    NSString *str2 = [d5Str substringToIndex:8];
    return  [NSString stringWithFormat:@"%@%@",str1,str2];
}


@end

// 匹配正则表达式
@implementation Tools (matchRegex)
//验证
+ (BOOL)regexWithText:(NSString*)text regex:(NSString*)regex{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self matches %@",regex];
    return [predicate evaluateWithObject:text];
}

//1,验证输入的内容是否是中文
+ (BOOL)isChinese:(NSString*)text{
    return [self regexWithText:text regex:@"(^[\u4e00-\u9fa5]+$)"];
}

//2,验证身份证号码格式
+ (BOOL)isRightIDNumber:(NSString*)idNumber{
   return  [self regexWithText:idNumber regex:@"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$"];
}

//3,验证手机号码格式
+ (BOOL)isRightMobileNumber:(NSString*)mobileNumber{
    return [self regexWithText:mobileNumber regex:@"^(17[0-9]|13[0-9]|14[0-9]|15[0-9]|18[0-9])\\d{8}$"];
}


@end

//判断网络连接是否可用
@implementation Tools (isNetworkReachability)
+ (BOOL)isNetworkReachability{
    AFNetworkReachabilityManager *manager =[AFNetworkReachabilityManager sharedManager];
    if(manager.isReachable) return YES;
//    [SVProgressHUD showInfoWithStatus:@"网络无法连接"];
    [MBProgressHUD showInfoMessage:@"网络无法连接"];
    return NO;
}
@end

//@implementation Tools (GesturePassword)
//+ (void)saveGesturePassword:(NSString*)password;{
//    NSString *md5Str = [Tools MD5:password];
//    [[NSUserDefaults standardUserDefaults]setObject:md5Str forKey:PHONE];
//    //保存后设置为有效，操作错误失效后没有安全密码的情况记为无效
//    [[NSUserDefaults standardUserDefaults]setValue:@"valide" forKey:ValideKey];
//    [[NSUserDefaults standardUserDefaults]synchronize];
//}
//+ (NSString*)getGesturePassword;{
//    return [[NSUserDefaults standardUserDefaults]objectForKey:PHONE];
//}
//+ (BOOL)isSameTolocalPasswordCompareWithPassword:(NSString*)password;
//{
//    NSString *localPassword = [[NSUserDefaults standardUserDefaults]objectForKey:PHONE];
//    if([[Tools MD5:password] isEqualToString:localPassword]){
//        return YES;
//    }
//    return NO;
//}
//+ (void)removeGesturePassword;{
//    if([Tools getGesturePassword]){
//        //手势密码的保存以当前登录的手机号码为key
//        [[NSUserDefaults standardUserDefaults]removeObjectForKey:PHONE];
//        //删除后标记为无效 用于区分没有设置安全密码的情况
//        [[NSUserDefaults standardUserDefaults]setValue:@"unvalide" forKey:ValideKey];
//        [[NSUserDefaults standardUserDefaults]synchronize];
//        
//    }
//}
//+ (NSString*)valideGesturePassword{
//    NSString *valideStr = [[NSUserDefaults standardUserDefaults]objectForKey:ValideKey];
//    return valideStr;
//}
//MD5加密
//+ (NSString *)MD5:(NSString *)str
//{
//    const char *cStr = [str UTF8String];
//    unsigned char result[16];
//    CC_MD5(cStr,strlen(cStr),result);
//    NSString *d5Str = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
//            result[0],result[1],result[2],result[3],result[4],result[5],result[6],result[7],
//            result[8],result[9],result[10],result[11],result[12],result[13],result[14],result[15]];
//    DLog(@"MD5--%@",d5Str);
//    NSString *str1 = [d5Str substringFromIndex:8];
//    NSString *str2 = [d5Str substringToIndex:8];
//    return  [NSString stringWithFormat:@"%@%@",str1,str2];
//}
//@end


